﻿using AutoMapper;
using BW.MesProject.Public.Domain.RBAC;
using BW.MesProject.Public.ErrorCode;
using BW.MesProject.Public.Infrastructure;
using BW.MesProject.WareHouse.Domain;
using BW.MesProject.WareHouse.Infrastructure;
using BW.MesProject.WareHouse.Infrastructure.Dto.Input;
using BW.MesProject.WareHouse.Infrastructure.Dto.OutPut;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace BW.MesProject.WareHouse.Application
{
    /// <summary>
    /// 外部标签解析
    /// </summary>
    public class LabelServices : ILabelServices
    {
        /// <summary>
        /// 外部标签解析类
        /// </summary>
        private readonly IBaseRepository<LabelModel> _Label;
        /// <summary>
        /// 供应商类
        /// </summary>
        private readonly IBaseRepository<SupplierModel> _Supplier;
        /// <summary>
        /// 标签代码
        /// </summary>
        private readonly IBaseRepository<TagParseRulesModel> _TagParse;
        private readonly IMapper _mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="Label">外部标签解析</param>
        /// <param name="Supplier">供应商</param>
        /// <param name="TagParse">解析标签分类</param>
        /// <param name="mapper">AutoMapper</param>
        public LabelServices(IBaseRepository<LabelModel> Label, IBaseRepository<SupplierModel> Supplier, IBaseRepository<TagParseRulesModel> TagParse, IMapper mapper)
        {
            _Label = Label;
            _Supplier = Supplier;
            _TagParse = TagParse;
            this._mapper = mapper;
        }
        /// <summary>
        /// 新增外部标签
        /// </summary>
        /// <param name="LabelModel">外部标签信息</param>
        /// <returns>操作结果</returns>
        public ApiResult<int> AddLabel(LabelModel LabelModel)
        {
            try
            {
                //判断外部标签编码，名称，供应商，解析规则是否为空
                if (string.IsNullOrEmpty(LabelModel.LalId) || string.IsNullOrEmpty(LabelModel.LabName) || string.IsNullOrEmpty(LabelModel.SupplierId.ToString()) || string.IsNullOrEmpty(LabelModel.Format.ToString()))
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "请检查外部标签编码，名称，供应商，解析规则是否为空"
                    };
                }
                var model = _Label.GetValue(x => x.LalId == LabelModel.LalId);
                if (model != null && !string.IsNullOrEmpty(model.LalId))
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "外部标签编号重复，请重新检查修改！！！"
                    };
                }
                //model = _Label.GetValue(x => x.LabName == LabelModel.LabName);
                //if (model != null && string.IsNullOrEmpty(model.LabName))
                //{
                //    return new ApiResult<int>()
                //    {
                //        Code = ApiEnums.Fail,
                //        Message = "外部标签名称重复，请重新检查修改！！！"
                //    };
                //}

                LabelModel.LId = YitIdHelper.NextId();

                //添加
                var models = _mapper.Map<LabelModel>(LabelModel);

                return new ApiResult<int>
                {
                    Code = ApiEnums.Success,
                    Message = "添加成功",
                    Data = _Label.Add(LabelModel),
                    TotalCount = 0
                };
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"添加外部标签时发生异常: {ex.Message}");

                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"添加失败: {ex.Message}",
                    Data = 0,
                    TotalCount = 0
                };
            }
        }

        /// <summary>
        /// 删除外部标签
        /// </summary>
        /// <param name="Id">外部标签主键ID</param>
        /// <returns>操作结果</returns>
        public ApiResult<int> DeleteLabel(long Id)
        {
            // 参数验证
            if (Id == 0)
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = "无效的外部标签ID",
                    Data = 0,
                    TotalCount = 0
                };
            }

            try
            {
                // 根据id查询外部标签信息
                var model = _Label.GetValue(x => x.LId == Id);

                // 检查是否存在
                if (model == null)
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "未找到指定的外部标签信息",
                        Data = 0,
                        TotalCount = 0
                    };
                }

                // 删除前检查是否有关联的其他信息
                // TODO: 如果有其他关联表，需要检查是否有关联数据

                // 执行删除操作
                int result = _Label.Delete(model);

                if (result > 0)
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Success,
                        Message = "删除成功",
                        Data = result,
                        TotalCount = 0
                    };
                }
                else
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "删除失败",
                        Data = 0,
                        TotalCount = 0
                    };
                }
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"删除外部标签时发生异常: {ex.Message}");

                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"删除失败: {ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 查询外部标签
        /// </summary>
        /// <param name="qryInput">查询传参</param>
        /// <returns></returns>
        public ApiResult<List<LabelOut>> GetLabel(QryInput qryInput)
        {
            try
            {
                int totalCount = 0;

                // 获取所有外部标签
                var list = _Label.GetAll();


                if (qryInput.PageSize == 0)
                {

                    list = list.OrderBy(u => u.LalId).Where(x=>x.SupplierId==qryInput.QryID);
                }
                else
                {

                    // 按编码查询
                    if (!string.IsNullOrEmpty(qryInput.QryID) && !string.IsNullOrEmpty(qryInput.QryName))
                    {
                        list = list.Where(x => x.LalId.Contains(qryInput.QryID) && x.LabName.Contains(qryInput.QryName));
                    }
                    else if (!string.IsNullOrEmpty(qryInput.QryID))
                    {
                        list = list.Where(x => x.LalId.Contains(qryInput.QryID));
                    }
                    else if (!string.IsNullOrEmpty(qryInput.QryName))
                    {
                        list = list.Where(x => x.LabName.Contains(qryInput.QryName));
                    }


                }
                // 处理结果数据
                var result = new List<LabelOut>();

                // 联表查询供应商，创建人员等信息
                var query1 = list.LeftJoin<SupplierModel>((a, b) => a.SupplierId == b.SupplierId).LeftJoin<UserModel>((a, b, c) => a.CreatedBy == c.UserId).Select((a, b, c) =>
                     new LabelOut
                     {
                         LId = a.LId,//主键ID
                         LalId = a.LalId,//外部标签ID
                         LabName = a.LabName,//外部标签名称 
                         SupplierId = b.SupplierId,//供应商编码
                         SupplierName = b.SupplierName,//供应商名称
                         Format = a.Format,
                         FormatMemo = a.Format,
                         Delimiter = a.Delimiter,
                         IsEnable = a.IsEnable,
                         Memo = a.Memo,//描述
                         EMPID = c.UserId,
                         EMPName = c.UserName,
                         CreatedBy = a.CreatedBy,
                         CreatedTime = a.CreatedTime,
                         UpdatedTime = a.UpdatedTime,
                         IsDeleted = a.IsDeleted,
                     });

                var queryList = query1?.ToList();
                // 初始化空列表，避免null引用
                List<TagParseRulesModel> TagList = new List<TagParseRulesModel>();

                // 如果有外部表标签解析有数据，才去查询标签类型
                if (list.Count() > 0)
                {
                    try
                    {
                        // 只有在需要时才查询标签数据
                        if (_TagParse != null)
                        {
                            TagList = _TagParse.GetAll()?.ToList() ?? new List<TagParseRulesModel>();
                        }

                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"查询关联数据时发生异常: {ex.Message}");
                        // 继续使用空列表
                    }
                }

                for (int i = 0; i < queryList.Count(); i++)
                {
                    if (!string.IsNullOrEmpty(queryList[i].Format) && TagList.Count > 0)
                    {
                        try
                        {

                            // 分割标签解析规则ID
                            var Tags = queryList[i].Format
                                .Split(',', StringSplitOptions.RemoveEmptyEntries)
                                .Select(id => id.Trim())
                                .ToList();

                            // 获取关联标签解析规则信息，保持与Tags相同的顺序
                            var relatedEmps = Tags
                                .Select(tagId => TagList.FirstOrDefault(p => p.TagParseRulesId == tagId))
                                .Where(tag => tag != null)
                                .ToList();

                            // 如果有关联标签解析规则，取第一个作为主要标签解析规则
                            if (relatedEmps.Count > 0)
                            {
                                // 如果有多个标签解析规则，可以考虑在备注中添加其标签解析规则信息
                                if (relatedEmps.Count >= 1)
                                {
                                    var otherFormat = string.Join(", ", relatedEmps.Select(p => $"({p.TagParseRulesId}){p.TagParseRulesName}"));
                                    var otherFormatMemo = string.Join(", ", relatedEmps.Select(p => $"[{p.TagParseRulesName}{queryList[i].Delimiter}]"));
                                    queryList[i].Format = otherFormat;

                                    queryList[i].FormatMemo = otherFormatMemo;
                                }
                            }
                            else
                            {
                                // 如果找不到标签解析规则，至少保标签解析规则ID
                                queryList[i].FormatMemo = queryList[i].FormatMemo;
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"处理标签解析规则信息时发生异常: {ex.Message}");
                            // 保留原始标签解析规则ID
                            queryList[i].FormatMemo = queryList[i].FormatMemo;
                        }
                    }
                }

                // 计算总数量
                totalCount = queryList.Count();

                // 分页处理
                if (qryInput.PageSize > 0)
                {
                    queryList = queryList
                        .OrderBy(a => a.LalId).ThenBy(x => x.CreatedTime)
                        .Skip((qryInput.PageNum - 1) * qryInput.PageSize)
                        .Take(qryInput.PageSize)
                        .ToList();
                }

                return new ApiResult<List<LabelOut>>()
                {
                    Code = ApiEnums.Success,
                    Message = "查询成功",
                    Data = queryList,
                    TotalCount = totalCount,
                    PageNum = qryInput.PageNum,
                    PageSize = qryInput.PageSize
                };

            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"查询外部标签时发生异常: {ex.Message}");

                return new ApiResult<List<LabelOut>>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"查询失败: {ex.Message}",
                    Data = new List<LabelOut>(),
                    TotalCount = 0
                };
            }
        }

        /// <summary>
        /// 修改外部标签
        /// </summary>
        /// <param name="model">外部标签信息</param>
        /// <returns>操作结果</returns>
        public ApiResult<int> UpdateLabel(LabelModel model)
        {
            try
            {
                //根据id查询是否有这条数据没有就修改不了
                var query = _Label.GetValue(x => x.LalId == model.LalId);
                if (query == null)
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "修改失败，未找到指定的外部标签信息",
                        Data = 0,
                        TotalCount = 0
                    };
                }

                //保存添加人和添加时间，添加修改人和修改时间
                _Label.Update(model);

                return new ApiResult<int>()
                {
                    Code = ApiEnums.Success,
                    Message = "修改成功",
                    Data = 1,
                    TotalCount = 0
                };
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"修改外部标签时发生异常: {ex.Message}");

                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"修改失败: {ex.Message}",
                    Data = 0
                };
            }
        }


        /// <summary>
        /// 修改启用
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ApiResult<int> UpdateEnable(LabelModel model)
        {
            var IsEnable = model.IsEnable;
            //根据id修改逻辑删除为 false
            model = _Label.GetValue(x => x.LId == model.LId);
            model.IsEnable = IsEnable;
            var Message = string.Empty;
            if (IsEnable)
            {
                Message = "启用成功";
            }
            else
            {
                Message = "停用成功";
            }
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = Message,
                Data = _Label.Update(model),
                TotalCount = 0
            };

        }
        /// <summary>
        /// 软删除（修改状态）
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public ApiResult<int> UpdateDelete(long Id)
        {
            //根据id修改逻辑删除为 false
            var model = _Label.GetValue(x => x.LId == Id);
            model.IsDeleted = true;
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = "删除成功",
                Data = _Label.Update(model),
                TotalCount = 0
            };
        }

        /// <summary>
        /// 查询表是否有该编码
        /// </summary>
        /// <param name="Label"></param>
        /// <returns></returns>
        public ApiResult<int> GetLabelID(string LabelId)
        {
            var model = _Label.GetValue(x => x.LalId == LabelId);
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = "成功",
                Data = 1,
                TotalCount = 0
            };

        }
    }
}
